<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/30
 * Time: 17:44
 */

namespace App\Models;

class AllInPayTooles{
    static $certFile = '';//通联公钥证书
    static $privateKeyFile = '';//商户私钥证书
    const password = '111111';//商户私钥密码以及用户密码
//	const  apiUrl = 'http://172.16.1.11:8080/aipg/ProcessServlet';//通联系统对接请求地址（内网）
    public $arrayXml ;
//    const apiUrl = 'http://113.108.182.3/aipg/ProcessServlet';//通联系统对接请求地址（外网,商户测试时使用）
//	const apiUrl = 'https://tlt.allinpay.com/aipg/ProcessServlet';//（生产环境地址，上线时打开该注释）
    static $apiUrl = '';

    public function __construct()
    {
        $this->arrayXml = new ArrayAndXml();
        if(env('WEB_URL')=='https://www.fbw-china.com/')
        {
            self::$certFile = base_path('allinpay-pds.pem');
            self::$privateKeyFile = base_path('20042100000795904.pem');
            self::$apiUrl = 'https://tlt.allinpay.com/aipg/ProcessServlet';
        }
        else
        {
            self::$certFile = base_path('allinpay-pds-test.pem');
            self::$privateKeyFile = base_path('20060400000044502-test.pem');
            self::$apiUrl = 'http://113.108.182.3/aipg/ProcessServlet';
        }
    }

    /**
     * PHP版本低于 5.4.1 的在通联返回的是 GBK编码环境使用
     * 但是本地文件编码是 UTF-8
     *
     * @param string $hexstr
     * @return binary string
     */
    public function hextobin($hexstr) {
        $n = strlen($hexstr);
        $sbin = "";
        $i = 0;

        while($i < $n) {
            $a = substr($hexstr, $i, 2);
            $c = pack("H*",$a);
            if ($i==0) {
                $sbin = $c;
            } else {
                $sbin .= $c;
            }

            $i+=2;
        }

        return $sbin;
    }

    /**
     * 验签
     */
    public function verifyXml($xmlResponse){

        // 本地反馈结果验证签名开始
        $signature = '';
        if (preg_match('/<SIGNED_MSG>(.*)<\/SIGNED_MSG>/i', $xmlResponse, $matches)) {
            $signature = $matches[1];
        }

        $xmlResponseSrc = preg_replace('/<SIGNED_MSG>.*<\/SIGNED_MSG>/i', '', $xmlResponse);
        $xmlResponseSrc1 = mb_convert_encoding(str_replace('<','&lt;',$xmlResponseSrc), "UTF-8", "GBK");
//        print_r ('验签原文');
//        print_r ($xmlResponseSrc1);
        $pubKeyId = openssl_get_publickey(file_get_contents(self::$certFile));
        $flag = (bool) openssl_verify($xmlResponseSrc, hex2bin($signature), $pubKeyId);
        openssl_free_key($pubKeyId);
        //echo '<br/>'+$flag;
        if ($flag) {
//            echo '<br/>Verified: <font color=green>Passed</font>.';


            // 变成数组，做自己相关业务逻辑
            $xmlResponse = mb_convert_encoding(str_replace('<?xml version="1.0" encoding="GBK"?>', '<?xml version="1.0" encoding="UTF-8"?>', $xmlResponseSrc), 'UTF-8', 'GBK');

            $results = $this->arrayXml->parseString( $xmlResponse , TRUE);
//            echo "<br/><br/><font color=blue>-------------华丽丽的分割线--------------------</font><br/><br/>";
//		    echo $results;
            return $results;
        } else {
//            echo '<br/>Verified: <font color=red>Failed</font>.';
            return FALSE;
        }
    }

    /**
     * 验签
     */
    public function verifyStr($orgStr,$signature){
//        echo '签名原文:'.$orgStr;
        $pubKeyId = openssl_get_publickey(file_get_contents(self::$certFile));
        $flag = (bool) openssl_verify($orgStr, hex2bin($signature), $pubKeyId);
        openssl_free_key($pubKeyId);

        if ($flag) {
//            echo '<br/>Verified: <font color=red>SUCC</font>.';
            return TRUE;
        } else {
//            echo '<br/>Verified: <font color=red>Failed</font>.';
            return FALSE;
        }
    }

    /**
     * 签名
     */
    public function signXml($params){
        $xmlSignSrc = $this->arrayXml->toXmlGBK($params, 'AIPG');
        $xmlSignSrc=str_replace("TRANS_DETAIL2", "TRANS_DETAIL",$xmlSignSrc);
//		echo ($xmlSignSrc);
        $privateKey = file_get_contents(self::$privateKeyFile);

        $pKeyId = openssl_pkey_get_private($privateKey, self::password);
        openssl_sign($xmlSignSrc, $signature, $pKeyId);
        openssl_free_key($pKeyId);

        $params['INFO']['SIGNED_MSG'] = bin2hex($signature);

        $xmlSignPost = $this->arrayXml->toXmlGBK($params, 'AIPG');

        return  $xmlSignPost;
    }
    /**
     * 发送请求
     */
    public function send($params){
        $xmlSignPost=$this->signXml($params);
        $xmlSignPost=str_replace("TRANS_DETAIL2", "TRANS_DETAIL",$xmlSignPost);
        $response = cURL::factory()->post(self::$apiUrl, $xmlSignPost);

        if (! isset($response['body'])) {
            die('Error: HTTPS REQUEST Bad.');
        }
        //获取返回报文
        $xmlResponse = $response['body'];
//        print_r("返回报文如下：");
//		print_r(str_replace('<','&lt;',$xmlResponse));
        //验证返回报文
        $result=$this->verifyXml($xmlResponse);
        return $result;
    }

    public function getPayActionModel($allinpaynumber,$shopid,$money,$cardnumber,$cardname,$summary,$remark)
    {
        if(!$allinpaynumber || !$shopid || !$money || !$cardnumber || !$cardname || !$summary || !$remark)
        {
            return false;
        }
//        header('Content-Type: text/html; Charset=UTF-8');
//        $tools=new AllInPayTooles();
// 源数组
        if(strlen($cardname)>12)
        {
            $account_prop = '1';
        }
        else
        {
            $account_prop = '0';
        }
        if(env('WEB_URL')=='https://www.fbw-china.com/')
        {
            $USER_NAME = '20042100000795904';
            $USER_PASS = '111111';
            $REQ_SN = '200421000007959-' . $allinpaynumber;
            $MERCHANT_ID = '200421000007959';
        }
        else
        {
            $USER_NAME = '20060400000044502';
            $USER_PASS = '`12qwe';
            $REQ_SN = '200604000000445-' . $allinpaynumber;
            $MERCHANT_ID = '200604000000445';
        }
        $params = array(
            'INFO' => array(
                'TRX_CODE' => '100014',
                'VERSION' => '03',
                'DATA_TYPE' => '2',
                'LEVEL' => '6',
                'USER_NAME' => $USER_NAME,
                'USER_PASS' => $USER_PASS,
                'REQ_SN' => $REQ_SN,
            ),
            'TRANS' => array(
                'BUSINESS_CODE' => '09900',
                'MERCHANT_ID' => $MERCHANT_ID,
                'SUBMIT_TIME' => date('YmdHis',time()),
                'E_USER_CODE' => $shopid,
//                'BANK_CODE' => '0105',
                'ACCOUNT_TYPE' => '00',
                'ACCOUNT_NO' => $cardnumber,
                'ACCOUNT_NAME' => $cardname,
                'ACCOUNT_PROP' => $account_prop,
                'AMOUNT' => $money * 100,
                'CURRENCY' => 'CNY',
                'ID_TYPE' => '0',
//                'CUST_USERID' => '2901347',
                'SUMMARY' => $summary,
                'REMARK' => $remark,
            ),
        );
//发起请求
        $result = $this->send( $params);
        if($result!=FALSE){
            return $result;
//            echo  '验签通过，请对返回信息进行处理';
//            echo $result['AIPG']['INFO']['RET_CODE'];
            //下面商户自定义处理逻辑，此处返回一个数组
        }else {
            return false;
        }
    }

    public function getPayStatus($allinpaynumber)
    {
        if(env('WEB_URL')=='https://www.fbw-china.com/')
        {
            $USER_NAME = '20042100000795904';
            $USER_PASS = '111111';
            $REQ_SN = '200421000007959-' . $allinpaynumber;
            $MERCHANT_ID = '200421000007959';
        }
        else
        {
            $USER_NAME = '20060400000044502';
            $USER_PASS = '`12qwe';
            $REQ_SN = '200604000000445-' . $allinpaynumber;
            $MERCHANT_ID = '200604000000445';
        }
        $params = array(
            'INFO' => array(
                'TRX_CODE' => '200004',
                'VERSION' => '03',
                'DATA_TYPE' => '2',
                'LEVEL' => '6',
                'USER_NAME' => $USER_NAME,
                'USER_PASS' => $USER_PASS,
                'REQ_SN' => $REQ_SN,
            ),
            'QTRANSREQ' => array(
                'QUERY_SN' => $REQ_SN,
                'MERCHANT_ID' => $MERCHANT_ID,
                'STATUS' => '2',
                'TYPE' => '1',
                'START_DAY' => '',
                'END_DAY' => ''
            ),
        );
        $result = $this->send( $params);
        return $result;
    }
}